<template>
  <div class="list-page">
    <div class="page-header">
      <div class="list-title">数字人生成列表</div>
      <div class="refresh-section">
        <el-button 
          type="primary" 
          :icon="Refresh" 
          @click="handleRefresh"
          :loading="loading"
        >
          刷新
        </el-button>
        <div v-if="hasProcessingTasks" class="status-hint">
          💡 有任务处理中，点击刷新获取最新状态
        </div>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-wrapper">
      <el-icon class="is-loading" :size="32"><Loading /></el-icon>
      <span>加载中...</span>
    </div>

    <div v-else class="list-content">
      <el-empty v-if="list.length === 0" description="暂无数据" />
      <el-card v-else v-for="item in list" :key="item.id" class="list-card" shadow="hover">
        <div class="video-wrapper" 
          @mouseenter="handleMouseEnter(item)"
          @mouseleave="handleMouseLeave(item)">
          <!-- 当status=2（已完成）且有视频URL时，直接显示视频；或者有视频URL且正在悬停时显示视频 -->
          <video 
            v-if="item.video_url && (item.status === 2 || item.isHovering)"
            :src="item.video_url"
            class="preview-video"
            loop
            controls
            preload="metadata"
            ref="videoRef"
          ></video>
          <div v-else class="default-cover">
            <el-icon :size="32"><VideoCamera /></el-icon>
          </div>
        </div>
        <div class="info">
          <div class="info-row">
            <span class="label">任务ID：</span>
            <span class="value">{{ item.task_id }}</span>
          </div>
          <div class="info-row">
            <span class="label">来源：</span>
            <span class="value">{{ item.avatar_source_text }}</span>
          </div>
          <div class="info-row">
            <span class="label">音频：</span>
            <span class="value">{{ item.audio_source_text }}</span>
          </div>
          <div class="info-row">
            <span class="label">状态：</span>
            <el-tag :type="getStatusType(item.status)">{{ item.status_text }}</el-tag>
          </div>
          <div class="info-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(item.create_time) }}</span>
          </div>
          <div v-if="item.error_msg" class="error-msg">
            错误信息: {{ item.error_msg }}
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 分页器 -->
    <div v-if="!loading && list.length > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoCamera, Loading, Refresh } from '@element-plus/icons-vue'
import { apiRequest, API_CONFIG } from '../../config/api.js'
import { useRouter } from 'vue-router'

const router = useRouter()

// 数据列表
const list = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const loading = ref(false)

// 计算是否有正在处理的任务
const hasProcessingTasks = computed(() => {
  return list.value.some(item => item.status === 0 || item.status === 1)
})

// 获取数据列表
const getList = async () => {
  console.log('开始获取列表数据...')
  loading.value = true
  
  try {
    const params = new URLSearchParams({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    console.log('请求参数:', params.toString())
    
    const response = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_GENERATION_HISTORY}?${params.toString()}`, {
      method: 'GET'
    })
    
    console.log('API响应:', response)

    if (response?.code === 200 && response?.data) {
      list.value = response.data.data.map(item => ({
        ...item,
        isHovering: false
      }))
      total.value = response.data.total
      console.log('数据处理完成，列表长度:', list.value.length)
    } else {
      console.error('API响应异常:', response)
      ElMessage.error(response?.msg || '获取列表失败')
      list.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取列表失败:', error)
    ElMessage.error('获取列表失败，请稍后重试')
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理鼠标悬停
const handleMouseEnter = (item) => {
  // 只有当状态不是2（已完成）且有视频URL时才设置悬停状态
  if (item.video_url && item.status !== 2) {
    item.isHovering = true
  }
}

const handleMouseLeave = (item) => {
  // 只有当状态不是2（已完成）时才清除悬停状态
  if (item.status !== 2) {
    item.isHovering = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 待处理
    1: '',        // 处理中
    2: 'success', // 已完成
    3: 'danger'   // 失败
  }
  return statusMap[status] || 'info'
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 刷新功能
const handleRefresh = () => {
  getList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 页面加载时获取数据
onMounted(() => {
  console.log('组件已挂载，准备获取数据...')
  getList()
})
</script>

<style scoped>
.list-page {
  padding: 32px 24px;
  background: #18181c;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.list-title {
  font-size: 22px;
  font-weight: bold;
  color: #fff;
  margin: 0;
}

.refresh-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-hint {
  font-size: 12px;
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid rgba(64, 158, 255, 0.2);
}



.list-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 24px;
}

.list-card {
  background: #23232a;
  border-radius: 14px;
  color: #fff;
  border: none;
  transition: transform 0.2s;
  overflow: hidden;
}

.list-card:hover {
  transform: translateY(-2px);
}

.video-wrapper {
  height: 240px;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: -20px -20px 16px -20px;
  overflow: hidden;
}

.preview-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #000;
}

.default-cover {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  background: #000;
}

.info {
  padding: 0 12px;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
}

.label {
  color: #909399;
  width: 80px;
  flex-shrink: 0;
}

.value {
  color: #e0e0e0;
  flex: 1;
  word-break: break-all;
}

.error-msg {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 8px;
  padding: 8px;
  background: rgba(245, 108, 108, 0.1);
  border-radius: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding: 24px;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: #fff;
  --el-pagination-button-color: #fff;
  --el-pagination-button-bg-color: #2a2a2a;
  --el-pagination-button-disabled-color: #606266;
  --el-pagination-button-disabled-bg-color: #2a2a2a;
  --el-pagination-hover-color: #409eff;
  --el-pagination-button-hover-bg-color: #32323a;
  --el-pagination-button-hover-color: #409eff;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 去除分页组件的所有边框 */
:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next),
:deep(.el-pagination button) {
  background: #2a2a2a !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}

:deep(.el-pagination .btn-prev:hover),
:deep(.el-pagination .btn-next:hover),
:deep(.el-pagination button:hover) {
  background: #32323a !important;
  color: #409eff !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination .el-pager li) {
  background: #2a2a2a !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #32323a !important;
  color: #409eff !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #409eff !important;
  color: #fff !important;
  border: none !important;
  box-shadow: none !important;
}

:deep(.el-pagination__sizes .el-input__wrapper), :deep(.el-pagination__sizes .el-select__wrapper) {
  background-color: #23232a !important;
  box-shadow: 0 0 0 1px #2a2a2a !important;
  border: none !important;
}
:deep(.el-pagination__sizes .el-input__inner) {
  color: #fff !important;
}
:deep(.el-pagination__sizes .el-select-dropdown) {
  background-color: #23232a !important;
  border: 1px solid #2a2a2a !important;
}
:deep(.el-pagination__sizes .el-select-dropdown__item) {
  color: #909399 !important;
}
:deep(.el-pagination__sizes .el-select-dropdown__item.selected) {
  color: #409eff !important;
  background-color: #2a2a2a !important;
}

.loading-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  padding: 48px;
  color: #909399;
}

:deep(.el-empty) {
  background: rgba(255, 255, 255, 0.02);
  padding: 48px;
  border-radius: 8px;
  color: #909399;
}
</style> 